﻿
function require(p, onload) {
    var path = require.resolve(p);
    var mod = require.modules[path];

    /*避免重复加载*/
    if (!mod) {
        // 同步加载JS脚本
        $.ajax({
            url: path + '.js',
            dataType: "text",
            async: (onload!=undefined),
            success: function (scr, status, xhr) {
                // 合成CommonJS导出模块的语法
                var srcCode = 'require.modules[\'' + path + '\'] = function(module, exports, require){\n' + scr + '\n}';
                eval(srcCode);
                console.log('脚本执行成功：' + path + '.js');
                
                mod = require.modules[path];
                if (!mod) throw new Error('failed to require "' + p + '"');
                
                if (!mod.exports) {
                    mod.exports = {};
                    mod.call(mod.exports, mod, mod.exports, require.relative(path));
                }

                if(onload) {
                    onload(mod.exports);
                }
            },
            error: function (xhr, status, err) {
                // 异常处理
                throw new Error('脚本加载异常, 状态码: ' + xhr.status + ' , 错误描述 : ' + err);
            }
        });
    }

    if(onload) {
        return undefined;
    } else {
        return mod.exports;
    }
}

require.modules = {};

require.resolve = function (path) {
    var orig = path;
    var reg = path + '.js';
    var index = path + '/index.js';
    return require.modules[reg] && reg
        || require.modules[index] && index
        || orig;
};

require.relative = function (parent, onload) {
    return function (p) {

        if ('.' != p.charAt(0)) return require(p);
        var path = parent.split('/');
        var segs = p.split('/');
        path.pop();

        for (var i = 0; i < segs.length; i++) {
            var seg = segs[i];
            if ('..' == seg) path.pop();
            else if ('.' != seg) path.push(seg);
        }

        //console.log('关联脚本引用：' + parent + '.js -> ' + p + '.js = ' + path.join('/') + '.js');
        return require(path.join('/'), onload);
    };
};

// 异步加载
function asyncRequire(p, onload) {
    require(p, onload);
}

// 同步加载
function syncRequire(p) {
    return require(p);
}

var exports = {};
